﻿using System;
using System.IO;
using System.Web.Security;

namespace RockPaperScissors.Web
{
    public partial class TeamUploader : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            SaveEntry(SettingsHelper.GetRoundNumber());
        }

        private void CreateDirectory(string teamName, int roundNumber)
        {
            string rootPath = Server.MapPath("/bots");
            string teamPath = string.Format("{0}\\{1}", rootPath, teamName);
            string roundPath = string.Format("{0}\\{1}", teamPath, roundNumber);

            if (!Directory.Exists(teamPath))
                Directory.CreateDirectory(teamPath);

            if (!Directory.Exists(roundPath))
                Directory.CreateDirectory(roundPath);
        }

        private void SaveEntry(int roundNumber)
        {
            string teamName = Membership.GetUser().UserName;
            string pathToSaveFile = Server.MapPath(string.Format("/bots/{0}/{1}/bot.dll", teamName, roundNumber));

            // make sure the file is valid before we upload it
            if (ValidFile(fupUploadBot))
            {
                try
                {
                    CreateDirectory(teamName, roundNumber);
                    fupUploadBot.SaveAs(pathToSaveFile);
                    this.Master.AddMessage("Your file has been uploaded", Message.Styles.Alert);
                }
                catch (Exception ex)
                {
                    this.Master.AddMessage(string.Format("Error uploading. {0}", ex.Message), Message.Styles.Alert);
                }
            }
        }

        private bool ValidFile(System.Web.UI.WebControls.FileUpload fupUploadBot)
        {
            bool tmpRtn = true;

            // make sure the file is less than 10 megs
            if (fupUploadBot.FileBytes.Length > 10485760) 
            {
                this.Master.AddMessage("Error! File is too large, under 10mb please.", Message.Styles.Alert); 
                return false;
            }

            if (!fupUploadBot.FileName.ToLower().Contains(".dll"))
            {
                this.Master.AddMessage("Error! You must upload a dll.", Message.Styles.Alert);
                return false;
            }

            // return
            return true;
        }
    }
}